#include <stdio.h>
#include "cllist.h"

#define INVALID_ELEM -2
#define OUT_ELEM -1

CLList josephus_init(SIZE_T num)
{
    CLList list;
    POSITION p;

    list = createCLList();

    if (list  == NULL)
    {
        return NULL;
    }

    ELEMTYPE x = 1;
    SIZE_T i = 1;

    while (i <= num)
    {
        appendElemCLList(list, x);
/*
        if (i >= num/2 && i <= num - 1)
        {
            p = locateVertexCLList(list, x);
            setElemValueCLList(list, p, OUT_ELEM);
        }
*/
        i++;
        x++;
    }
    
    return list;
}

ELEMTYPE getElemValueCLList(CLList list, POSITION p)
{
    if (list == NULL)
    {
        #ifdef DEBUG
        printf("=============ELEM VALUE===========\n");
        printf("LIST or POSITION IN INVALID\n");
        printf("=============ELEM VALUE===========\n");
        #endif
        return INVALID_ELEM;
    }
    
    #ifdef DEBUG
    printf("=============ELEM VALUE===========\n");
    printf("VALUE = %d, POSITION = %u\n", p->info, p);
    printf("=============ELEM VALUE===========\n");
    #endif

    return p->info;
}

int setElemValueCLList(CLList list, POSITION p, ELEMTYPE x)
{
    if (list == NULL)
    {
        return -1;
    }
    
    if (p != NULL)
    {
        p->info = x;
        return 1;
    }
    
    return 0;
}

SIZE_T getNextOutJosephus(CLList list, SIZE_T start, SIZE_T count)
{
    SIZE_T i, index;
    SIZE_T length;
    POSITION p;

    if (list == NULL)
    {
        return -1;
    }

    // count should great or equal than 1
    i = count - 1;

    length = lengthCLList(list);

    index = start;
    for (i = count - 1; i > 0; i--)
    {
        index = (index+1) > length ? (index + 1)%length : index + 1;
        if (index == 0)
        {
            index = 1;
        }
    }

    p = getPositionByIndexCLList(list, index);
    #ifdef DEBUG
    printf("CURRENT INDEX = %d, NEXT INDEX = %d\n", start, index);
    #endif
    return (index);
}

POSITION getLastOutJosephus(CLList list, SIZE_T start, SIZE_T count)
{
    SIZE_T total;
    SIZE_T i, next;
   
    POSITION p;
    ELEMTYPE x;

    if (list == NULL)
    {
        return NULL;
    }
    total = lengthCLList(list);

    next = start;

    while (total > 0)
    {
        next = getNextOutJosephus(list, next, count);
        p = getPositionByIndexCLList(list, next);
        x = getElemValueCLList(list, p);
        printf("%d is out\n", x);
        deleteVertexCLList(list, p);
        if (next >= lengthCLList(list))
        {
            next = 1;
        }
        printCLList(list);
        total--;
    }
}

int main ()
{
    CLList list;
    POSITION p;
    ELEMTYPE x;
    int i = 0;
    SIZE_T N, s, m, next;
    
    scanf("%d%d%d", &N, &s, &m);

    list = josephus_init(N);

    if (list != NULL)
    {
        //appendElemCLList(list, 99);

        printCLList(list);
        getLastOutJosephus(list, s, m);
        destroyCLList(&list);
    }
    return 0;
}
